<?php

/**
 * @category   MM
 * @package    MM_Service
 */
class MM_Service_Admin_Event extends Mediad2_Service_Abstract
{
	/**
	 * 初始化
	 */
	public function init()
	{
		$this->setMapper('MM_Mapper_Event');
		$this->setModel('MM_Model_Event');
	}
	
	/**
	 * create event
	 * @param array $params
	 * @return Mediad2_Model_Result
	 */
	public function createEvent($params)
	{
		//var
		if (!isset($params['uid']) || empty($params['uid'])) {
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'Miss parameter: uid');
		}
		$uid = $params['uid'];
		$type = $this->decideEventTypeByUid($uid);
		
		//封装event model
		$event = new MM_Model_Event();
		//填充必须项
		$event->setUid($uid);
		$event->setName($params['name']);
		$event->setStartdate($params['startdate']);
		$event->setEnddate($params['enddate']);
		$event->setType($type);
		//$event->setStatus(MM_Model_Event::STATUS_NEW);
		$event->setStatus($params['status']);//change by vincent
		$event->setAddtime(time());
		$event->setFollowercount(0);
		$event->setJoincount(0);
		$event->setQrcode('');
		$event->setUpdatetime($event->getAddtime());
		$event->setLasttime($event->getAddtime());
		//填充非必须项
		$event->setTitle(isset($params['title'])?$params['title']:'');
		$event->setSubtitle(isset($params['subtitle'])?$params['subtitle']:'');
		$event->setDesc(isset($params['desc'])?$params['desc']:'');
		$event->setWeibotopics(isset($params['weibotopics'])?$params['weibotopics']:'');
		$event->setAvatar(isset($params['avatar'])?$params['avatar']:'');
		$event->setSummary(isset($params['summary'])?$params['summary']:'');
		$event->setWebsite(isset($params['website'])?$params['website']:'');
		$event->setWeibo(isset($params['weibo'])?$params['weibo']:'');
		$event->setTele(isset($params['tele'])?$params['tele']:'');
		$event->setEmail(isset($params['email'])?$params['email']:'');
		$event->setSharecontent(isset($params['sharecontent'])?$params['sharecontent']:'');		
		
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
	
		try {			
			//insert event
			$mapper = $this->getMapper();
			$eid = $mapper->insert($event->toArray());
	
			//get qrcode
			$qrcode = $this->getFunctions()->encodeQrcode($eid,4);
	
			//update event
			$event->setEid($eid);
			$event->setQrcode($qrcode);
			$mapper->update($event->toArray());
	
			//insert event_address
			$address = new MM_Model_EventAddress();
			$address->setEid($eid);
			$address->setCity(isset($params['city'])?$params['city']:'');
			$address->setAddress(isset($params['address'])?$params['address']:'');
			$address->setLng(isset($params['lng'])?$params['lng']:0);
			$address->setLat(isset($params['lat'])?$params['lat']:0);
			
			$serviceAddress = new MM_Service_Admin_EventAddress();
			$serviceAddress->getMapper()->insert($address->toArray());
	
			//提交事务
			$db1->commit();
	
			//赋值
			$data = array(
					'eid' 		=> $eid,
					'qrcode'	=> $qrcode,
			);
	
			//返回结果--成功
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
	
		} catch (Zend_Exception $e) {
	
			//回滚
			$db1->rollBack();
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
	
		}
	}
	
	/**
	 * 更新event信息
	 * @param int $eid
	 * @param array $params
	 * @param MM_Model_Event $model
	 * @return Mediad2_Model_Result
	 */
	public function updateEvent($eid,$params)
	{
		try {
			//获取指定id的event
			$result = $this->find($eid);
			if ($result->getCode()==$result::CODE_FAILURE) return $result;
			$event = $result->getData();
			
			//封装model
			if (isset($params['name'])) $event->setName($params['name']);
			if (isset($params['title'])) $event->setTitle($params['title']);
			if (isset($params['subtitle'])) $event->setSubtitle($params['subtitle']);
			if (isset($params['startdate'])) $event->setStartdate($params['startdate']);
			if (isset($params['enddate'])) $event->setEnddate($params['enddate']);
			if (isset($params['desc'])) $event->setDesc($params['desc']);
			if (isset($params['status'])) $event->setStatus($params['status']);
			if (isset($params['weibotopics'])) $event->setWeibotopics($params['weibotopics']);
			if (isset($params['avatar'])) $event->setAvatar($params['avatar']);
			if (isset($params['summary'])) $event->setSummary($params['summary']);
			if (isset($params['website'])) $event->setWebsite($params['website']);
			if (isset($params['weibo'])) $event->setWeibo($params['weibo']);
			if (isset($params['tele'])) $event->setTele($params['tele']);
			if (isset($params['email'])) $event->setEmail($params['email']);
			if (isset($params['sharecontent'])) $event->setSharecontent($params['sharecontent']);
			if (isset($params['updatetime'])) $event->setUpdatetime($params['updatetime']);
			if (isset($params['lasttime'])) $event->setLasttime($params['lasttime']);
			
			//更新event
			$this->update($event);
			
			//更新address model
			$serviceAddress = new MM_Service_Admin_EventAddress();
			$where = "eid = $eid";
			$resultA  = $serviceAddress->findBy($where);
			if ($resultA->getCode() == $resultA::CODE_FAILURE) return $resultA;
			$address = $resultA->getData();
			$address->setCity(isset($params['city'])?$params['city']:'');
			$address->setAddress(isset($params['address'])?$params['address']:'');
			$address->setLng(isset($params['lng'])?$params['lng']:0);
			$address->setLat(isset($params['lat'])?$params['lat']:0);
			
			//更新address
			$serviceAddress->getMapper()->update($address->toArray());
			
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE); //返回结果--失败
		}
	}
	
	/**
	 * delete event
	 * @param int $eid
	 * @param int $uid
	 * @return Mediad2_Model_Result
	 */
	public function delEvent($eid, $uid)
	{		
		try {
			//封装where
			$where = "eid = $eid AND uid = $uid";
			$row = array(
					'status' => MM_Model_Event::STATUS_DELETED,
			);
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
		
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
		
		} catch (Zend_Exception $e) {
		
			//出错处理
			$this->handleException($e);
		
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * follow event
	 * @param int $eid
	 * @param int $uid
	 * @return Mediad2_Model_Result
	 */
	public function followEvent($eid, $uid)
	{
		//流程：
		//1. 在event_follower中增加一条关注者的记录
		//2. 活动的关注者总数加1
		//3. 返回指定活动的信息
		
		//var
		$serviceEventFollower = new MM_Service_Admin_EventFollower();
		
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
	
		try {
			if (!$this->isFollowedEvent($eid, $uid)) {
				//在event_follower中增加一条记录
				$follower = new MM_Model_EventFollower();
				$follower->setEid($eid);
				$follower->setUid($uid);
				$follower->setAddtime(time());
				$follower->setIsdel($follower::ISDEL_NO);
				$follower->setDeltime(0);
				$serviceEventFollower->getMapper()->insert($follower->toArray());
				
				//活动的关注者总数加1
				$row = array(
						'followercount' => new Zend_Db_Expr("followercount + 1"),
				);
				$where = "eid = $eid And status <> " . MM_Model_Event::STATUS_DELETED;
				$mapper = $this->getMapper();
				$mapper->__updateSQL($row, $where);
				
			}
			
			//获取指定活动的信息
			$result = $this->find($eid);
			if ($result->getCode()==$result::CODE_SUCCESS) {
				$data = $result->getData();
				$this->result = $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data->toArray());
			} else {
				$this->result = $result;
			}
			
			//提交事务
			$db1->commit();
				
			return $this->result;
	
		} catch (Zend_Exception $e) {
			
			//回滚事务
			$db1->rollback();
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	
	}
	
	/**
	 * join event
	 * @param int $eid
	 * @param int $uid
	 * @param array $requestData
	 * @return Mediad2_Model_Result
	 */
	public function joinEvent($eid, $uid,$requestData = null)
	{
		//流程：
		//1. 在event_user中增加一条记录
		//2. 活动的参与者总数加1
		
		//var
		$serviceEventUser = new MM_Service_Admin_EventUser();
		$mmUser = new Mediad2_Service_Admin_User();
		$user_isVerify = false;
		
		//httpdata		
		$nickname 	= @$requestData['nickname'];
		$mobile 	= @$requestData['mobile'];		
		$email 		= @$requestData['email'];		
		$fail 		= Mediad2_Model_Result::CODE_FAILURE;
		
		//验证用户绑定身份[verify]
		//判断是否绑定用户[verify][1][如果是绑定用户则不对用户邮箱进行处理]		
		$userResult = $mmUser->find($uid);
		if(!$userResult->getCode())//系统错误返回 
			return $this->returnResult($fail,"moblie system error 300");
		
		$moblieUser = $userResult->getData();
		if($moblieUser->getVerifystatus()){
			$user_isVerify = true;
		}
		
		//验证邮箱[verify][2][不是绑定用户需要验证用户邮箱的唯一性,并返回结果]
		if(!$user_isVerify){
			/* $validate = new Zend_Validate_EmailAddress();
			if(!$validate->isValid($email)) //验证邮箱格式错误返回
				return $this->returnResult($fail,"email format is wrong"); */
			$m = new Mediad2_Service_Admin_User();
			$rst = $m->findBy(sprintf("email = '%s'",$email));
			if(!$rst->getCode())//系统错误返回 			
				return $this->returnResult($fail,"moblie system error 314");
			$dat = $rst->getData();
			$uu = $dat->getUid();
			if(isset($uu)) //邮箱已经存在返回				
				return $this->returnResult($fail,$email." address already used");
		}
		
		
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
			
		try {
			if ($this->isJoinedEvent($eid, $uid)==1) {
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,"already join");
			} else {
				//在event_user中增加一条记录
				$user = new MM_Model_EventUser();
				$user->setEid($eid);
				$user->setUid($uid);
				$user->setAddtime(time());
				$user->setIsdel($user::ISDEL_NO);
				$user->setDeltime(0);
				$serviceEventUser->insert($user);
				
				//活动的参与者总数加1
				$row = array(
						'joincount' => new Zend_Db_Expr("joincount + 1"),
				);
				$where = "eid = $eid And status = " . MM_Model_Event::STATUS_RELEASED; //状态为发布
				$mapper = $this->getMapper();
				$mapper->__updateSQL($row, $where);
				
				//参加会议时更新用户信息 by vincent 20130809
				if($userResult->getCode()){
					$u = new Mediad2_Model_User();
					$userModal = $userResult->getData();
					if($nickname)
					$userModal->setNickname($nickname);
					if($mobile)
					$userModal->setMobile($mobile);
					if(!$user_isVerify){//未绑定用户 [verify][3][进行绑定操作,仅此一次]
						$userModal->setEmail($email);
						$userModal->setVerifystatus(1);
					}
					$mmUser->update($userModal);
				}				
				
				//提交事务
				$db1->commit();
				
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,"user join");
			}
	
		} catch (Zend_Exception $e) {
			
			//回滚事务
			$db1->rollback();
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	
	}
	
	/**
	 * quit event
	 * @param int $eid
	 * @param int $uid
	 * @return Mediad2_Model_Result
	 */
	public function quitEvent($eid, $uid)
	{
		//流程：
		//1. 在event_user中更新对应的记录
		//2. 活动的参与者总数减1
		
		//var
		$serviceEventUser = new MM_Service_Admin_EventUser();
		
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
	
		try {
			if ($this->isJoinedEvent($eid, $uid)==1) {
				//在event_user中更新对应的记录
				/* $row = array(
						'isdel' => 1,
						'deltime' => time(),
				);
				$where = "isdel = 0 AND eid = $eid AND uid = $uid";
				$mapper = $serviceEventUser->getMapper();
				$mapper->__updateSQL($row, $where); */
				
				//直接删除活动 by vincent
				$where = "eid = $eid AND uid = $uid";
				$serviceEventUser->deleteBy($where);
				
				//活动的参与者总数减1
				$row = array(
						'joincount' => new Zend_Db_Expr("joincount - 1"),
				);
				$where = "eid = $eid And status = " . MM_Model_Event::STATUS_RELEASED; //状态为发布
				$mapper = $this->getMapper();
				$mapper->__updateSQL($row, $where);
			}
			
			//提交事务
			$db1->commit();
			
			//返回成功
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
			
			//回滚事务
			$db1->rollback();
	
			//出错处理
			$this->handleException($e);
	
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	
	}
	
	/**
	 * get event info 获取活动所有的信息
	 * @param int $eid
	 * @return Mediad2_Model_Result
	 */
	public function getEventInfo($eid)
	{
		$ok = Mediad2_Model_Result::CODE_SUCCESS;
		$r0 = $this->find($eid,true);//活动基本信息
		if($r0->getCode() == $ok){
			$address 	= new MM_Service_Admin_EventAddress();
			$venue 		= new MM_Service_Admin_EventVenue();
			$schedule 	= new MM_Service_Admin_EventSchedule();
			$guest 		= new MM_Service_Admin_EventGuests();
			$content 	= new MM_Service_Admin_EventContent();
			$contact 	= new MM_Service_Admin_EventContact();
						
			$where = sprintf("eid = '%s'",$eid);
			$group = "gid";
			
			$r1 = $address->findBy($where,null,true);//活动地址
			$r2 = $venue->getCount($where);
			$r3 = $schedule->getCount($where);
			$r4 = $guest->getCount($where,$group);
			$r5 = $content->getCount($where);
			$r6 = $contact->fetchAll(null,null,$where,null,true);
			$r7 = $content->findBy($where." and ectype = '8'",null,true);//关于我们
			if($r1->getCode() == $ok){
				$data["event"] 			= $r0->getData();
				$data["event_address"] 	= $r1->getData();
				$data["venue"] 			= $r2->getData();
				$data["schedule"] 		= $r3->getData();
				$data["guest"] 			= $r4->getData();
				$data["content"] 		= $r5->getData();
				$data['contact'] 		= $r6->getData();
				$data['aboutus'] 		= $r7->getData();
				return $this->returnResult($ok,"get all data",$data);
			}else{
				return $r1;
			}
		}else{
			return $r0;
		}
	}
		
	/**
	 * 根据uid获取所有活动ids
	 * @param string $uid
	 * @author vincent
	 */
	public function getEventIds($uid)
	{
		$ok = Mediad2_Model_Result::CODE_SUCCESS;
		$fail = Mediad2_Model_Result::CODE_FAILURE;
		$where = sprintf("uid = '%s'",$uid);
		$order = 'startdate desc';
		$result = $this->fetchAll(1,999,$where,$order,true);
		$ids = null;
		if($result->getCode() == $ok){
			$array = $result->getData();
			if(count($array)!=0){
				foreach ($array as $key => $value) {
					$ids[] = $array[$key]['eid'];	
				}
				return $this->returnResult($ok,"getall",$ids);
			}
			return $this->returnResult($fail,"empty");
		}
		return $result;
		
	}
	
	/**
	 * 根据uid获取用户参加过的所有活动ids [event_user]
	 * @param string $uid
	 * @author vincent
	 */
	public function getEventUserIds($uid)
	{
		$ok = Mediad2_Model_Result::CODE_SUCCESS;
		$fail = Mediad2_Model_Result::CODE_FAILURE;
		$where = sprintf("uid = '%s' and isdel = 0",$uid);
		$eventuser = new MM_Service_Admin_EventUser();
		$result = $eventuser->fetchAll(1,999,$where,null,true);
		$ids = null;
		if($result->getCode() == $ok){
			$array = $result->getData();
			if(count($array)!=0){
				foreach ($array as $key => $value) {
					$ids[] = $array[$key]['eid'];
				}
				return $this->returnResult($ok,"getall",$ids);
			}
			return $this->returnResult($fail,"empty");
		}
		return $result;
	
	}
	
	/**
	 * 根据活动code显示所属用户的所有公开活动的列表 [event]
	 * @param string $code
	 * @author vincent
	 */
	public function getEventByCode($code)
	{
		$ok = Mediad2_Model_Result::CODE_SUCCESS;
		$fail = Mediad2_Model_Result::CODE_FAILURE;		
		$where = sprintf("qrcode = '%s'",$code);
		$result = $this->fetchAll(1,999,$where,null,true);
		$uid = null;
		if($result->getCode() == $ok){
			$eventData = $result->getData();
			if(count($eventData)!=0)
			$uid = $eventData[0]['uid'];
		}
		if(isset($uid)){//仅显示公开活动
			$sql = sprintf("uid = '%s' AND type = 1",$uid);
			$order = "startdate desc";
			return $this->fetchAll(null,null,$sql,$order,true);
		}else{
			return $this->returnResult($fail,"no user info");
		}	
	}
	
	/**
	 * 根据code生成活动app
	 * @param string $code
	 * @author vincent
	 */
	public function getapp($code)
	{
		//流程：
		//1.生成MM二维码APK
		//2.返回结果Apk的下载URL
	
		try {
			//1.生成渠道APK
			//执行批处理命令，生成推广APK
			$command = APK_PATH . "makemm.bat $code";
			@system( $command );
	
			//检查APK文件是否存在
			$apkUrl = null;
			$apkName =$code . ".apk";					//apk文件名
			$apkDir = APK_PATH . "mm\\";				//apk文件存放目录
			if (file_exists($apkDir . $apkName)) {
				$apkUrl = DOWNLOAD_PATH . "mm/". $apkName;		//构造URL
			}
			if (empty($apkUrl)) {
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE); //返回结果--失败
			} else {
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$apkUrl);//返回结果--成功
			}
	
		} catch (Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE); //返回结果--失败
		}
	}		
	
	/**
	 * 指定用户是否已加入活动
	 * @param int $eid
	 * @param int $uid
	 * @return int 
	 */
	public function isJoinedEvent($eid, $uid)
	{
		//var
		$serviceEventUser = new MM_Service_Admin_EventUser();
	
		$where = "isdel = 0 AND eid = $eid AND uid = $uid "; //存在于eventuser表中，且未退出
		$row = $serviceEventUser->getMapper()->getCount($where);
		return $row;
	}
	
	/**
	 * 指定用户是否已关注活动
	 * @param int $eid
	 * @param int $uid
	 * @return boolean
	 */
	public function isFollowedEvent($eid, $uid)
	{
		//var
		$serviceEventFollower = new MM_Service_Admin_EventFollower();
	
		$where = "isdel = 0 AND eid = $eid AND uid = $uid "; //存在于eventfollower表中
		$row = $serviceEventFollower->getMapper()->getCount($where);
		if (empty($row)) {
			return false;
		} else {
			return true;
		}
	}
	
	//---------------------------------------
	// 私有方法
	//---------------------------------------
	
	/**
	 * 通过uid获得指定用户的角色类型
	 * @param int $uid
	 * @return int
	 */
	private function decideEventTypeByUid($uid)
	{
		$type = MM_Model_Event::TYPE_PERSONAL;	//默认是个人活动
		
		$serviceUser = new Mediad2_Service_Admin_User();
		$result = $serviceUser->find($uid);
		if ($result->getCode()==$result::CODE_SUCCESS) {
			$user = $result->getData();
			$rolecode = $user->getRolecode();
			switch ($rolecode) {
				case Mediad2_Model_Role::ROLECODE_CORP:
					$type = MM_Model_Event::TYPE_CORP;
					break;
				default:
					break;
			}
		}
		return $type;
	}
	

	
}